from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import db
from info.models import News, Comment, CommentLike
from info.moduels.news import news_blu
from info.utils.common import user_data_info
from info.utils.response_code import RET


@news_blu.route("/news/comment_like",methods = ["POST"])
@user_data_info
def comment_like():
    """
    评论点赞
    :return:
    """
    user= g.user
    if  not user:
        return jsonify(errno = RET.SESSIONERR,errmsg = "用户未登陆")

    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    if not all ([comment_id,action]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = "数据参数错误")

    if action not in ["add","remove"]:
        return jsonify(errno=RET.DATAERR, errmsg="数据参数错误")

    comment_cm = Comment.query.get(comment_id)
    if not comment_cm:
        return jsonify(errno=RET.NODATA, errmsg="数据库无数据")

    # 点赞
    if action == "add":
        comment_li = CommentLike.query.filter(CommentLike.comment_id == comment_id,CommentLike.user_id == user.id).first()

        if not comment_li:
            comment_li = CommentLike()
            comment_li.comment_id = comment_id
            comment_li.user_id = user.id
            db.session.add(comment_li)
        comment_cm.like_count += 1
    # 取消点赞
    else:
        comment_li = CommentLike.query.filter(CommentLike.comment_id == comment_id,CommentLike.user_id == user.id).first()
        db.session.delete(comment_li)
        comment_cm.like_count -= 1

    return jsonify(errno = RET.OK,errmsg = "OK")


@news_blu.route("/news/news_comment",methods= ["POST"])
@user_data_info
def comment_news():
    """
    评论新闻和回复评论
    :return:
    """
    user = g.user
    user_id = user.id
    if  not user:
        return jsonify(errno = RET.SESSIONERR,errmsg = "用户未登陆")

    # 1.获取数据
    news_id = request.json.get("news_id")
    comment_content = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 2.判断数据
    if not all ([news_id,comment_content]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    # 3.查询数据--判断是否有这个新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    if not news:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    # 4.初始化评论模型
    comment = Comment()
    comment.user_id = user_id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        # 这里需要手动提交是因为系统自动提交是在return之后---但是我在return之前需要用到这些数据--所以需要自己提交
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = "数据参数错误")

    return jsonify(errno = RET.OK,errmsg = "OK",data = comment.to_dict())



@news_blu.route("/news/news_collect",methods=["POST"])
@user_data_info
def news_collect():
    """
    点赞和取消点赞
    1.获取数据
    2.校正数据
    3.查询数据,修改数据
    4.响应
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno = RET.SESSIONERR,errmsg= "用户未登录")

    # 1.获取数据
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.校正数据
    if not all ([news_id,action]):
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    if action not in ("collect","cancel_collect"):
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    # 3.查询数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    # 4.收藏与取消收藏
    # 取消收藏
    if action == "cancel_collect":
        user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)

    return jsonify(errno = RET.OK,errmsg = "OK")





# 新闻详情页
@news_blu.route("/<int:news_id>")
@user_data_info
def news_detail(news_id):
    # 通过装饰器来获取用户的信息--g--应用上下文的生命周期是一次请求(视图函数中)
    user = g.user

    # 查询点击排行的新闻内容
    news = News.query.order_by(News.clicks.desc()).limit(6)

    # 判断是否查询到数据
    if  not news:
        return jsonify(errno = RET.DATAERR,errmsg = "数据错误")

    news_list_dict = []
    for new in news:
        news_list_dict.append(new.to_dict())

    # 通过新闻id来获取新闻详情
    news = News.query.get(news_id)

    # 点击数加1
    news.clicks += 1

    # 判断是否查询到数据
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg="数据错误")

    # 默认用户是没有收藏的
    is_collected = False
    # 判断用户是否登陆
    if user:
        # 通过user来查询用户收藏过那些新闻,判断当前的新闻在不在收藏里面
        if news in user.collection_news:
            is_collected = True


    # 查询当前新闻的所有评论
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据库查询失败")

    # 跟新用户点赞的评论
    comment_like_ids = []
    if user:
        # 查看当前用户在当前新闻的点赞评论
        # 1.查看当前新闻的所有评论
        comment_id = [comment.id for comment in comments]
        # 2.评论中属于用户的评论
        comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_id),
                                                 CommentLike.user_id == user.id).all()

        print(comment_likes)
        # 3.取到用户点赞的所有评论的id
        comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]

    # 是否关注
    is_followed = False
    if news.user and user:
        if news.user in user.followers:
            is_followed = True



    # 跟新用户的评论
    comments_dict_li = []
    for comment in comments:
        # comments_dict_li.append(comment.to_dict())
        comment_dict = comment.to_dict()
        # 如果用户点赞的评论在
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comments_dict_li.append(comment_dict)

    data = {
        "user": user.to_dict() if user else None,
        "news_list_dict": news_list_dict,
        "new_li":news.to_dict(),
        "is_collected":is_collected,
        "comments":comments_dict_li,
        "is_followed":is_followed
    }
    return  render_template("news/detail.html",data = data)
